import React, {useEffect, useLayoutEffect, useState} from 'react';
import Layout from '../components/Layout';
import Type from '../components/Type';
import Amount from '../components/Amount';
import Category from '../components/Category';
import PickDate from '../components/PickDate';
import Notes from '../components/Notes';
import KeyPad from '../components/KeyPad';
import styled from 'styled-components';
import dayjs from 'dayjs';

const TallyWrapper = styled.div`
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: 100%;
`;

const OptionsSection = styled.div`
    flex-grow: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
`;

const Tally = () => {
    // 选项
    const [selectedType, setSelectedType] = useState<('outcome' | 'income')>('outcome');
    const [selectedCategory, setSelectedCategory] = useState<string>();
    const [selectedDate, setSelectedDate] = useState<{ day: number, month: number, year: number }>({
        day: dayjs().date(),
        month: dayjs().month() + 1,
        year: dayjs().year()
    });
    const [notes, setNotes] = useState('');

    // 金额
    const [expression, setExpression] = useState<string>('');    // 金额表达式
    const [totalAmount, setTotalAmount] = useState<string>('');   //总金额

    // 金额字符串过长时锁定禁止输入
    const [overLengthLock, setOverLengthLock] = useState(false);

    // expression归零时，其他选项也执行重置操作
    useEffect(() => {
        setExpression('');
        setSelectedDate({
            day: dayjs().date(),
            month: dayjs().month() + 1,
            year: dayjs().year()
        });
        setNotes('');
    }, [selectedType]);



    // 每次expression变化，重新计算 totalAmount 的值
    useLayoutEffect(() => {
        let result: number = 0;
        expression.split('+').forEach((item) => {
            if (item !== '') {
                result += parseFloat(item);
            }
        });
        const resultString = `${result.toFixed(2)}`
        if (resultString.length > 11) {
            setOverLengthLock(true)
            setExpression((expression) => expression.slice(0, -1))
        } else {
            setOverLengthLock(false)
            setTotalAmount(resultString);
        }
    }, [expression]);

    const handleTypeChange = (newType: ('outcome' | 'income')) => {
        setSelectedType(newType);
    };

    const handleCategoryChange = (category: string) => {
        setSelectedCategory(category);
    };

    const handleDateChange = (date: { day: number, month: number, year: number }) => {
        setSelectedDate(date);
    };

    const handleNotesChange = (notes: string) => {
        setNotes(notes);
    };

    const handleExpressionChange = (newExpression: string) => {
        setExpression(newExpression);
    };

    function commitData() {
        // 点击「确定」后提交数据
        // 收集数据
        if (totalAmount === '' || parseFloat(totalAmount) === 0) {
            alert('亲，0元咱就别记了，不丢人嘛');
            setTotalAmount('')
        } else {
            const data = {
                type: selectedType,
                category: selectedCategory,
                date: (selectedDate.year === dayjs().year() && selectedDate.month === dayjs().month() && selectedDate.day === dayjs().date()
                    ? dayjs().toISOString()
                    : dayjs(`${selectedDate.year}-${selectedDate.month}-${selectedDate.day}`).toISOString()),
                amount: totalAmount,
                notes: notes !== '' ? notes : '无'
            };
            console.log(data);
            alert('记了一笔账，好开心啊!')

            // 清空数据
        }
    }

    return (
        <Layout>
            <TallyWrapper>
                <Type
                    selectedType={selectedType}
                    onTypeChange={handleTypeChange}
                />
                <OptionsSection>
                    <Amount
                        selectedType={selectedType}
                        amount={totalAmount}
                        expression={expression}
                    />
                    <Category
                        selectedType={selectedType}
                        selectedCategory={selectedCategory}
                        onSelectedCategoryChange={handleCategoryChange}
                    />
                    <PickDate
                        selectedDate={selectedDate}
                        onSelectedDateChange={handleDateChange}
                    />
                    <Notes
                        notes={notes}
                        onNotesChange={handleNotesChange}
                    />
                </OptionsSection>
                <KeyPad
                    overLengthLock={overLengthLock}
                    expression={expression}
                    onExpressionChange={handleExpressionChange}
                    commitData={commitData}
                />
            </TallyWrapper>
        </Layout>
    );
};

export default Tally;